﻿using System;
using System.Collections.ObjectModel;
using Icinetic.FeedCategorySample.Common.Base;
using Icinetic.FeedCategorySample.Entities;
using Icinetic.FeedCategorySample.ViewModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;

namespace Icinetic.FeedCategorySample
{
    public sealed partial class CoverPage : LayoutAwarePage
    {
        public CoverPage()
        {
            this.InitializeComponent();
            DataContext = new CoverPageViewModel();

            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.Parameter != null)
                Model.LoadItemsList(e.Parameter as ObservableCollection<Category>);
            else
                await Model.LoadCategoryList();
            flipView.Loaded += FlipView_Loaded;
        }

        public CoverPageViewModel Model
        {
            get { return DataContext as CoverPageViewModel; }
        }

        private void FlipView_Loaded(object sender, RoutedEventArgs e)
        {
            flipView.SelectedIndex = Model.SelectedIndex;
            flipView.Loaded -= FlipView_Loaded;
        }

        private void MenuButton_Click(object sender, RoutedEventArgs e)
        {
            appBarZoomIn.IsOpen = false;
            this.Frame.Navigate(typeof(MainPage));
        }

        private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
        {
            RssItem target = (sender as Grid).DataContext as RssItem;
            NavigateToArticle(target);
        }

        private void snappedControl_ItemClick(object sender, ItemClickEventArgs e)
        {
            var target = e.ClickedItem as RssItem;
            NavigateToArticle(target);
        }

        private void NavigateToArticle(object target)
        {
            Frame frame = Window.Current.Content as Frame;
            Model.SelectedIndex = flipView.SelectedIndex;
            frame.Navigate(typeof(ArticlePage), target);
        }
    }
}
